import json
import uuid

from tornado.web import Application,RequestHandler
from tornado.ioloop import  IOLoop
from tornado.options import options,define,parse_command_line

class LoginHandler(RequestHandler):
    users =[{
        'id': 1,
        'name':'disen',
        'pwd': '123',
        'last_login_device':'Android 5.1 OnePlus5'

    }]
    def set_default_headers(self):
        #所有的请求方法执行后,默认设置的响应头的信息
    #以下设置响应头都是解决跨域问题
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', 'content-type,x-requested-with')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT,DELETE')
    def get(self):
        #读取json数据
        bytes = self.request.body
        print(bytes)
        print(self.request.headers.get('content-type'))

        content_type=self.request.headers.get('content-type')
        if content_type.startswith('application/json'):
            # self.write('upload json ok')
            json_str = bytes.decode('utf-8')
            #反序列化
            json_data = json.loads(json_str)

            resp_data = {}
            login_user = None
            #查询用户名和口令是否正确

            for user in self.users:
                if user['name'] == json_data['name']:
                    if user['pwd'] == json_data['pwd']:
                        login_user =user
                        break

            if login_user:

                resp_data['msg']='success'
                resp_data['token'] = uuid.uuid4().hex
            else:
                resp_data['msg']='查无此用户'

            self.write(resp_data)
            self.set_header('content-type','application/json')
        else:
            self.write('upload  err,必须是json')
        print(bytes)

        # self.write('login')



    def post(self):
        pass
    def delete(self):
        pass
    def put(self):
        pass
    def options(self):
        #跨域请求时,会被客户端请求,用来表示服务器是否支持跨域请求
        self.set_status(200)

def make_app():
    return Application([
        ('/user',LoginHandler),

    ],default_host=options.h)

if __name__ == '__main__':
    define('p', default=8000, help='run on the given port', type=int)
    define('h', default='localhost', help='绑定主机IP', type=str)

    parse_command_line()#解释命令行参数
    app = make_app()
    app.listen(options.p)
    print('Running http://%s:%s/' % (options.h,options.p))
    IOLoop.current().start()